package com.things8.iot.common.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Arrays;

//import org.springframework.core.env.Profiles;

/**
 * Aspect for logging execution of service and repository Spring components.
 * <p>
 * By default, it only runs with the "dev" profile.
 */
@Aspect
@Component
public class LoggingAspect {



    private final Environment env;

    public LoggingAspect(Environment env) {
        this.env = env;
    }

    @Before("applicationPackagePointcut()")
    public void before(JoinPoint joinpoint) {
        logger(joinpoint).info(" ==============================< 类、方法进入 : {} >============================== ", joinpoint.getStaticPart());
        logger(joinpoint).info("接口入参 : {}", "params = " + Arrays.toString(joinpoint.getArgs()));
    }

    @AfterReturning(pointcut = "applicationPackagePointcut()", returning = "result")
    public void afterReturn(JoinPoint joinpoint, Object result) {
        logger(joinpoint).info("接口返回 : result = {}", result);
        logger(joinpoint).info(" ==============================< 方法调用结束 : {} >============================== ", joinpoint.getStaticPart());
    }

    /**
     * Pointcut that matches all repositories, services and Web REST endpoints.
     */
    @Pointcut("within(@org.springframework.stereotype.Repository *)" +
            " || within(@org.springframework.stereotype.Service *)" +
            " || within(@org.springframework.web.bind.annotation.RestController *)")
    public void springBeanPointcut() {
        // Method is empty as this is just a Pointcut, the implementations are in the advices.
    }

/*    @Pointcut("@annotation(org.springframework.web.bind.annotation.RestController) || @annotation(org.springframework.stereotype.Controller)")
    public void controllerPointcut() {

    }

    @Before("springBeanPointcut()")
    public void beforeController(JoinPoint joinPoint) {
        logger(joinPoint).info(" ==============================< 类、方法进入 : {} >============================== ", joinPoint.getStaticPart());
        logger(joinPoint).info("接口入参 :{}", "params = " + Arrays.toString(joinPoint.getArgs()));
    }*/

    /**
     * Pointcut that matches all Spring beans in the application's main packages.
     */
    @Pointcut("within(com.things8.iot..dao..*)" +
            " || within(com.things8.iot..service..*)" +
            " || within(com.things8.iot..controller..*)")
    public void applicationPackagePointcut() {
        // Method is empty as this is just a Pointcut, the implementations are in the advices.
    }

    /**
     * Retrieves the {@link Logger} associated to the given {@link JoinPoint}.
     *
     * @param joinPoint join point we want the logger for.
     * @return {@link Logger} associated to the given {@link JoinPoint}.
     */
    private Logger logger(JoinPoint joinPoint) {
        return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
    }

    /**
     * Advice that logs methods throwing exceptions.
     *
     * @param joinPoint join point for advice.
     * @param e         exception.
     */
    @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
//        if (env.acceptsProfiles(Profiles.of("dev"))) {
//            logger(joinPoint)
//                    .error(
//                            "Exception in {}() with cause = \'{}\' and exception = \'{}\'",
//                            joinPoint.getSignature().getName(),
//                            e.getCause() != null ? e.getCause() : "NULL",
//                            e.getMessage(),
//                            e
//                    );
//        } else {
            logger(joinPoint)
                    .error(
                            "Exception in {}() with cause = {}",
                            joinPoint.getSignature().getName(),
                            e.getCause() != null ? e.getCause() : "NULL"
                    );
//        }
    }

    /**
     * Advice that logs when a method is entered and exited.
     *
     * @param joinPoint join point for advice.
     * @return result.
     * @throws Throwable throws {@link IllegalArgumentException}.
     */
    @Around("applicationPackagePointcut() && springBeanPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Logger log = logger(joinPoint);
        if (log.isDebugEnabled()) {
            log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
        }
        try {
            Object result = joinPoint.proceed();
            if (log.isDebugEnabled()) {
                log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result);
            }
            return result;
        } catch (IllegalArgumentException e) {
            log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName());
            throw e;
        }
    }
}
